package com.fbinggun.dt;

import com.alibaba.fastjson.JSONObject;
import com.fbinggun.dt.gui.ChoiceGui;
import com.fbinggun.dt.gui.ChoiceProject;
import com.fbinggun.dt.gui.TaskGui;
import com.fbinggun.dt.player.PlayerData;
import com.fbinggun.dt.task.Task;
import com.fbinggun.dt.task.conditions.Conditions;
import com.fbinggun.fbinggunutil.*;
import com.fbinggun.sql.SQLite;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class DailyTask extends JavaPlugin {
    public static DailyTask plugin;

    public static Map<String, PlayerData> playerDataMap = new HashMap<>();
    public static Map<String, Task> taskMap = new HashMap<>();
    public static ChoiceGui choiceGui;
    public static TaskGui taskGui;
    public static FileConfiguration taskConfig;
    public static JsonTable table;
    private static SQLite sql;

    public static ChoiceProject getChoiceProject(String id) {
        return choiceGui.choiceProjectHashMap.get(id);
    }

    public static Task getTask(String TaskId) {
        return taskMap.get(TaskId);
    }

    public static PlayerData getPlayerData(Player player) throws SQLException, ClassNotFoundException {
        PlayerData playerData = playerDataMap.get(player.getName());
        if (playerData == null) {
            String jsonStr = table.getJson(player.getName());
            if (jsonStr == null) {
                playerData = new PlayerData(player);
                playerDataMap.put(player.getName(), playerData);
            } else {
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                if (jsonObject == null) {
                    playerData = new PlayerData(player);
                    playerDataMap.put(player.getName(), playerData);
                } else {
                    playerData = new PlayerData(player, jsonObject);
                    playerDataMap.put(player.getName(), playerData);
                }
            }
        }
        return playerData;
    }

    public void reload(){
        saveDefaultConfig();
        reloadConfig();
        try {
            sql=  SqlUtil.reloadSQL(this, getConfig().getConfigurationSection("SQL"));
            table = new JsonTable(sql, getConfig().getString("SQL.table"));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        taskConfig = ConfigUtil.load(this, new File(getDataFolder().getPath(),"Task.yml"));
        loadTask();
        choiceGui=new ChoiceGui(getConfig().getConfigurationSection("ChoiceGui"));
        taskGui=new TaskGui(getConfig().getConfigurationSection("TaskGui"));
    }

    @Override
    public void onEnable() {
        plugin = this;
        Conditions.loadTriggerType();
        PluginUtil.setupEconomy();
        getCommand("DailyTask").setExecutor(new TaskCommand());
        reload();
        new PAPI(this).register();

    }

    @Override
    public void onDisable() {
        try {
            unload();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public int getCount(Player player) {
        ConfigurationSection config = getConfig().getConfigurationSection("TaskCount");
        if (config == null) {
            return 1;
        }
        int count = config.getInt("Default");
        for (String key : config.getKeys(false)) {
            if (player.hasPermission("DailyTask." + key)) {
                if (count <= config.getInt(key)) {
                    count = config.getInt(key);
                }

            }
        }
        return count;
    }

    private void loadTask() {
        taskMap = new HashMap<>();
        if (taskConfig != null) {
            for (String taskId : taskConfig.getKeys(false)) {
                debug("载入任务："+taskId);
                taskMap.put(taskId, new Task(taskId, taskConfig.getConfigurationSection(taskId)));
            }
        }
    }

    public String getLang(String key){
        return PApiUtil.colorReplace(getConfig().getString("Lang."+key," "));
    }


    public void unload() throws SQLException, ClassNotFoundException {
        save();
        getServer().getScheduler().cancelTasks(this);
        HandlerList.unregisterAll(this);
        playerDataMap =new HashMap<>();
        choiceGui=null;
        taskGui=null;
        taskMap=new HashMap<>();
        sql.CloseSql();
        sql=null;
    }

    public void save() throws SQLException, ClassNotFoundException {
        if(playerDataMap!=null) {
            for (PlayerData playerData : playerDataMap.values()) {
            playerData.save();
            }
        }
    }
    public static void debug(String msg){
        if(plugin.getConfig().getBoolean("DeBug")){
            plugin.getLogger().info(msg);
        }
    }
}
